import { Component } from 'react';
import React from 'react';
import { connect } from 'umi';

import { PageContainer, PageHeaderWrapper } from '@ant-design/pro-layout';
import { TableListItem } from '@/pages/ListTableList/data';
import { Divider, Button, Switch,Modal,TreeSelect } from 'antd';
import { FormValueType } from '@/pages/ListTableList/components/UpdateForm';
import HighPerformTable from '@/components/HighPerformTable';
import KeywordFilterSearch from '@/components/KeywordFilterSearch';
import APIS from '@/apis';
import { PlusOutlined } from '@ant-design/icons';
import { DataNode } from 'rc-tree/lib/interface';
import { data } from 'jquery';
import { template } from 'lodash';

class RoleListPage extends Component<any, any> {
  actionRef: any;

  constructor(props: any) {
    super(props);
    this.state={
      modalVisible:false,
      currentRoleId:undefined,
      treeData:undefined,
      pers:undefined,
      currentId:-1
    }
  }
 

  componentDidMount() { 
    APIS.UserAPI.GetOnlyPermissionList().then((res)=>{
      
      // this.setState({treeData:res.data.records})
      const temp = [];
      this.OverrideData(temp,res.data.records)
      this.setState({treeData:temp})
    })
  }

  OverrideData(arr:Array<any>,data:any){
    data.map((item,index)=>{
       arr.push({
        title:item.name,
        value:item.permissionId,
        key:item.key,
        children:[]
      })
     if(item.children.length>0){
          this.OverrideData(arr[index].children,item.children)
      }
    })

  } 


  handleDelete(data: any) {
    return APIS.UserAPI.DeleteRole(data.roleId)
      .then(() => {
        return Promise.resolve(true);
      })
      .catch(() => {
        return Promise.resolve(false);
      });
  }

  handleChangeState(record: any, state: boolean) {
    return APIS.UserAPI.ChangeRoleState({ id: record.roleId, state: state ? 1 : 0 }).then(
      (response) => {
        return Promise.resolve(response.data.state === 1);
      },
    );
  }
  handleAdd(data: any) {
    return APIS.UserAPI.CreateNewRole({ name: data.name, isDef: data.isDef, desc: "" })
      .then(() => {
        return Promise.resolve(true);
      })
      .catch(() => {
        return Promise.resolve(false);
      });
  }
  handleUpdate(data: any) {
    return APIS.UserAPI.CreateNewRole({ name: data.name, isDef: data.isDef, desc: "" })
      .then(() => {
        return Promise.resolve(true);
      })
      .catch(() => {
        return Promise.resolve(false);
      });
  }

  handlePermissions(data:any){
    return APIS.UserAPI.UpdateRole({id:data.id ,pers:data.pers})
  }


  requestGetData(
    params: {
      pageSize?: number;
      current?: number;
    },
    sorter: {
      [key: string]: 'ascend' | 'descend';
    },
    filter: {
      [key: string]: React.ReactText[];
    },
  ) {
    return APIS.UserAPI.GetRoleList({ ...params, sorter, filter });
  }
  clomns: any = [
    {
      title: '角色名称',
      dataIndex: 'name',
      rules: [
        {
          required: true,
          message: '角色名称为必填项',
        },
      ],
    },
    {
      title: '角色描述',
      dataIndex: 'description',
      valueType: 'textarea',
    },
    {
      title: '默认角色',
      dataIndex: 'isDefault',
      valueEnum: {
        0: { text: "否" },
        1: { text: "是" }
      },
      render: (_: any, record: any) => (
        <>
          <Switch defaultChecked={record.isDefault}></Switch>
        </>
      ),
    },
    {
      title: '更新时间',
      dataIndex: 'desc',
      valueType: 'date',
      hideInFrom: true,
      renderText: () => <span>{new Date().toLocaleDateString()}</span>,

    },
    {
      title: '权限',
      render:(record:any)=>(
        <a onClick={()=>{this.setState({modalVisible:true,currentId:record.roleId});}}>
          修改权限
        </a>
      )
    },
  ];
  render() {
    const {currentId,pers} = this.state;
    return (
      <div>
        {/* <KeywordFilterSearch
          filters={[
            { title: '角色类型', multiple: false, keywords: ['全部', '教务管理员', '教师'] },
          ]}
        ></KeywordFilterSearch> */}

        <Modal
        title="修改权限"
        visible={this.state.modalVisible}
        onCancel={() => this.setState({modalVisible:false,pers:undefined})}
        onOk={()=>{this.handlePermissions({id:currentId,pers:pers});this.setState({modalVisible:false,pers:undefined})}}
        >
          <TreeSelect
            style={{width:"100%"}}
            placeholder='谨慎选择权限'
             treeData={this.state.treeData}
             value={this.state.pers}
             onChange={(value:any)=>{this.setState({pers:value})}}
             treeCheckable={true}
             showCheckedStrategy={"SHOW_PARENT"}

          />
        </Modal>

        <HighPerformTable
          requestGetData={this.requestGetData.bind(this)}
          ref={(ref) => (this.actionRef = ref)}
          columns={this.clomns}
          handleChangeState={this.handleChangeState.bind(this)}
          rowKey="roleId"
          handleDelete={this.handleDelete.bind(this)}
          handleUpdate={this.handleUpdate.bind(this)}
          handleAdd={this.handleAdd.bind(this)}
          toolBarRender={() => [
            <Button type="primary" onClick={() => this.actionRef.handleModalVisible(true)}>
              <PlusOutlined /> 新增角色
            </Button>,
          ]}
        ></HighPerformTable>
      </div>
    );
  }
}

export default connect()(RoleListPage);
